package com.origin.chaos.common.handler;

import com.origin.chaos.common.bean.vo.Result;
import com.origin.chaos.common.exception.NotLoginException;
import com.origin.chaos.common.exception.OutPutMsgException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @author: tao.ding
 * @date 2021-07-16
 */
@Slf4j
@RestControllerAdvice
public class CommonExceptionHandler {
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception var) {
        var.printStackTrace();
        if (var instanceof OutPutMsgException) {
            return Result.ofErrorMessage(var.getMessage());
        } else if (var instanceof NotLoginException) {
            return Result.notLogin();
        } else if (var instanceof org.springframework.web.bind.MethodArgumentNotValidException) {
            return Result.ofErrorMessage(((MethodArgumentNotValidException) var).getBindingResult().getAllErrors()
                    .stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(",")));
        } else if (var instanceof javax.validation.ConstraintViolationException) {
            return Result.ofErrorMessage(((ConstraintViolationException) var).getConstraintViolations()
                    .stream().map(ConstraintViolation::getMessageTemplate).collect(Collectors.joining(",")));
        }
        return Result.ofErrorMessage("服务器内部错误");
    }
}
